<template>
	<view class="layout">
		<wd-navbar title="分切复卷" left-text="返回" @click-left="uni.navigateBack" left-arrow right-text="保存" @click-right="onSubmit"/>
		<wd-toast />
		
		<!-- 工序记录状态显示 -->
		<wd-cell-group title="工序记录状态">
			<wd-cell v-if="hasExistingRecord" title="最后完成时间" :value="processRecord?.productionTime ? dayjs(processRecord.productionTime).format('YYYY-MM-DD HH:mm:ss') : ''" />
			
			<!-- 按规格显示基本信息 -->
			<template v-if="hasExistingRecord">
				<view v-for="(specInfo, index) in integratedSpecInfo" :key="index" class="spec-status-section">
					<!-- 规格基本信息 -->
					<wd-cell 
						:title="`规格${index + 1}${specInfo.specName ? ': ' + specInfo.specName : ''}`"
						:value="`${specInfo.length}米, ${specInfo.jointsCount}个接头`"
						class="spec-basic-info"
					/>
				</view>
			</template>
		</wd-cell-group>
		
		<wd-form ref="form" class="form" :model="formState">
			<wd-cell-group border>
				<view class="total-length">
					<text>总长度: {{ totalLength }} 米</text>
					<wd-button size="small" type="primary" @click="addSpecItem">添加规格</wd-button>
				</view>

				<view v-for="(item, index) in formState.specItems" :key="index" class="spec-item">
					<view class="spec-header">
						<text class="spec-title">规格 {{index + 1}}</text>
						<wd-button v-if="index > 0" size="small" type="danger" @click="formState.specItems.splice(index, 1)">删除</wd-button>
					</view>
					
					<!-- 规格选择/显示 -->
					<wd-input
						v-if="!hasExistingRecord || !item.specification"
						label="规格"
						v-model="item.specification"
						readonly
						:rules="[{ required: true, message: '请选择规格' }]"
						placeholder="点击选择规格"
						is-link
						@click="openSpecSelection(index)"
					/>
					<wd-input
						v-else
						label="规格"
						v-model="item.specification"
						readonly
						placeholder="已保存的规格"
						custom-style="background-color: #f7f8fa;"
					/>
					<wd-input 
						label="米数" 
						type="number" 
						clearable 
						v-model="item.length"
						placeholder="请输入生产米数" 
						:rules="[{ required: true, message: '请填写生产米数' }]"
					/>
					<wd-input 
						label="接头数" 
						clearable 
						v-model="item.linkCount" 
						type="number"
						placeholder="请输入接头数" 
						:rules="[{ required: true, message: '请填写接头数' }]" 
					/>
					
					<!-- 规格事件登记 -->
					<view class="spec-events">
						<view class="events-header">
							<text class="events-title">事件登记</text>
							<wd-button size="small" type="icon" icon="add" @click="openEventSheet(index)" />
						</view>
						<view v-if="item.events && item.events.length > 0" class="events-list">
							<wd-cell 
								v-for="(event, eventIndex) in item.events" 
								:key="eventIndex"
								:title="event.name"
								:value="dayjs(event.eventTime).format('YYYY-MM-DD HH:mm:ss')" 
								@click="removeEvent(index, eventIndex)" 
								is-link 
								class="event-item"
							/>
						</view>
						
						<!-- 显示该规格已存在的异常记录 -->
						<wd-cell 
							v-for="(exception, exIndex) in (integratedSpecInfo[index] && integratedSpecInfo[index].exceptions ? integratedSpecInfo[index].exceptions : [])" 
							:key="`exception-${index}-${exIndex}`"
							:title="`异常: ${exception.exceptionName}`"
							:value="exception.createTime ? dayjs(exception.createTime).format('YYYY-MM-DD HH:mm:ss') : ''"
						/>
					</view>
				</view>

				<wd-textarea 
					v-model="formState.note" 
					prop="note" 
					placeholder="请填写说明" 
				/>
			</wd-cell-group>
		</wd-form>
		
		<!-- 事件选择弹窗 -->
		<wd-action-sheet v-model="record.open" :actions="record.actions" @select="onSelect" />
		
		<!-- 规格选择弹窗 -->
		<wd-popup v-model="specSelectionOpen" position="bottom" :height="600" safe-area-inset-bottom>
			<view class="spec-popup">
				<view class="spec-popup-header">
					<text class="spec-popup-title">选择规格</text>
					<wd-button size="small" type="text" @click="specSelectionOpen = false">取消</wd-button>
				</view>
				
				<!-- 搜索框 -->
				<view class="spec-search">
					<wd-search 
						v-model="searchValue" 
						@change="onSearchChange" 
						placeholder="请输入型号或规格进行搜索" 
						:maxlength="50"
					/>
				</view>
				
				<!-- 规格列表 -->
				<wd-cell-group class="spec-list">
					<wd-cell 
						v-for="(spec, index) in filteredSpecifications" 
						:key="index"
						:title="spec.label"
						is-link
						@click="selectSpecification(spec)"
					/>
					<!-- 空状态 -->
					<view v-if="filteredSpecifications.length === 0" class="spec-empty">
						<text class="spec-empty-text">{{ searchValue ? '未找到匹配的规格' : '暂无规格数据' }}</text>
					</view>
				</wd-cell-group>
			</view>
		</wd-popup>
	</view>
</template>

<script setup lang="ts">
	import { reactive, ref, computed } from 'vue';
	import dayjs from 'dayjs';
	import { useToast } from '@/uni_modules/wot-design-uni'
	import { C91330326Ma287Bmm6JService, ExceptionService, ProcessService, type AddProcessStepRequest, type EditProcessStepRequest } from '@/services';
	import useApp from '@/stores/app';
	import { onLoad } from '@dcloudio/uni-app';
	
	const app = useApp();
	const toast = useToast();
	const STEP = 6;
	
	// 规格选项
	const specifications = ref([]);
	const allSpecifications = ref([]); // 保存所有规格数据
	const filteredSpecifications = ref([]); // 搜索过滤后的规格数据
	const searchValue = ref(''); // 搜索关键词
	const specSelectionOpen = ref(false); // 规格选择弹窗状态
	const currentSpecIndex = ref(-1); // 当前选择规格的索引
	
	// 加载小卷规格列表
	const loadSmallRollSpecs = async () => {
		try {
			const response = await ProcessService.getSmallRollSpecList();
			if (response.code === 200 && response.rows) {
				// 过滤有效数据并转换为格式：型号(规格)
				const specData = response.rows
					.filter(item => item.dataStatus === 1 && item.specification && item.model)
					.map(item => {
						// 组合格式：型号(规格)
						const displayText = `${item.model}(${item.specification})`;
						return {
							value: displayText,
							label: displayText,
							model: item.model,
							specification: item.specification,
							smallRollId: item.smallRollId // 保存小卷规格ID
						};
					});
				
				// 保存完整数据和过滤数据
				allSpecifications.value = specData;
				filteredSpecifications.value = [...specData];
				specifications.value = specData; // 保持兼容性
				console.log('加载到的规格选项:', specData.length, '个');
			} else {
				console.error('规格列表接口返回错误:', response.msg);
				allSpecifications.value = [];
				filteredSpecifications.value = [];
				specifications.value = [];
			}
		} catch (error) {
			console.error('加载规格列表失败:', error);
			allSpecifications.value = [];
			filteredSpecifications.value = [];
			specifications.value = [];
		}
	};

	onLoad(async () => {
		toast.loading('加载中...')
		try {
			if (!app.work?.events) {
				await app.loadWork();
			}
			// 先加载小卷规格列表（需要在加载工序记录之前完成，用于回显匹配）
			await loadSmallRollSpecs();
			// 加载异常事件数据
			await loadExceptionEvents();
			// 最后加载工序记录（依赖规格数据）
			await loadProcessStepRecord();
		} catch (error) {
			toast.error("网络出现异常!")
		} finally {
			toast.close();
		}
	});
	
	// 初始化表单数据
	const step = app.work?.step_6 ?? {
		workId: app.code || '',
		specItems: [{
			specification: '',
			length: 0,
			linkCount: 0,
			smallRollId: '', // 小卷规格ID
			events: [] // 每个规格都有自己的事件列表
		}],
		note: ''
	};
	
	const formState = reactive(step);
	const app_events = app.getEvents(STEP);
	const events = ref(app_events);
	
	// 计算总长度
	const totalLength = computed(() => {
		return formState.specItems.reduce((sum, item) => {
			return sum + (Number(item.length) || 0);
		}, 0);
	});
	
	// 整合规格信息（包含基本信息和异常事件）
	const integratedSpecInfo = computed(() => {
		if (!hasExistingRecord.value || !processRecords.value || processRecords.value.length === 0) {
			return [];
		}
		
		return processRecords.value.map((record, index) => {
			// 获取规格名称
			let specName = '';
			if (record.smallRollModel && record.smallRollSpecification) {
				specName = `${record.smallRollModel}(${record.smallRollSpecification})`;
			}
			
			// 获取该规格已保存的异常记录
			const specExceptions = savedExceptions.value[index] || [];
			
			return {
				specName: specName,
				length: record.productionLength || 0,
				jointsCount: record.jointsCount || 0,
				exceptions: specExceptions
			};
		});
	});
	
	// 添加规格项
	const addSpecItem = () => {
		formState.specItems.push({
			specification: '',
			length: 0,
			linkCount: 0,
			smallRollId: '', // 小卷规格ID
			events: [] // 新增规格时也要初始化事件列表
		});
	};
	
	// 搜索过滤规格
	const onSearchChange = ({ value }) => {
		searchValue.value = value;
		if (!value.trim()) {
			// 如果搜索为空，显示所有规格
			filteredSpecifications.value = [...allSpecifications.value];
		} else {
			// 根据关键词过滤规格（支持模糊搜索）
			filteredSpecifications.value = allSpecifications.value.filter(spec => 
				spec.label.toLowerCase().includes(value.toLowerCase()) ||
				spec.model.toLowerCase().includes(value.toLowerCase()) ||
				spec.specification.toLowerCase().includes(value.toLowerCase())
			);
		}
	};
	
	// 打开规格选择弹窗
	const openSpecSelection = (specIndex) => {
		currentSpecIndex.value = specIndex;
		searchValue.value = '';
		filteredSpecifications.value = [...allSpecifications.value];
		specSelectionOpen.value = true;
	};
	
	// 选择规格
	const selectSpecification = (spec) => {
		if (currentSpecIndex.value >= 0 && currentSpecIndex.value < formState.specItems.length) {
			formState.specItems[currentSpecIndex.value].specification = spec.value;
			formState.specItems[currentSpecIndex.value].smallRollId = spec.smallRollId; // 保存小卷规格ID
		}
		specSelectionOpen.value = false;
	};
	
	
	
	
	const record = reactive({
		open: false,
		actions: [],
		currentSpecIndex: -1 // 记录当前操作的规格索引
	});
	
	// 打开事件选择弹窗
	const openEventSheet = (specIndex) => {
		record.currentSpecIndex = specIndex;
		record.open = true;
	};
	
	// 选择事件
	const onSelect = ({ item, index }) => {
		if (record.currentSpecIndex >= 0 && record.currentSpecIndex < formState.specItems.length) {
			// 确保events数组存在
			if (!formState.specItems[record.currentSpecIndex].events) {
				formState.specItems[record.currentSpecIndex].events = [];
			}
			
			// 添加事件到对应的规格
			formState.specItems[record.currentSpecIndex].events.push({
				name: item.name,
				eventTime: dayjs(),
				step: STEP,
				specIndex: record.currentSpecIndex,
				exceptionId: item.exceptionId // 保存异常ID
			});
		}
		record.open = false;
	};
	
	// 移除事件
	const removeEvent = (specIndex, eventIndex) => {
		if (formState.specItems[specIndex].events) {
			formState.specItems[specIndex].events.splice(eventIndex, 1);
		}
	};
	
	// 工序记录状态
	const processRecord = ref<any>(null);
	const processRecords = ref<any[]>([]); // 存储所有工序记录
	const hasExistingRecord = ref(false);
	const savedExceptions = ref<any[]>([]); // 存储已保存的异常记录，按规格索引分组

	// 获取分切复卷工序的processId
	const getProcessId = async () => {
		try {
			const result = await ProcessService.getProcessList(1, 10);
			if (result.code === 200) {
				const process = result.rows.find(p => p.processName === '分切复卷');
				return process?.processId;
			}
		} catch (error) {
			console.error('获取工序列表失败:', error);
		}
		return null;
	};

	// 加载工序记录
	const loadProcessStepRecord = async () => {
		try {
			if (!app.code) {
				console.error('流程卡号不存在');
				return;
			}
			
			const processId = await getProcessId();
			if (!processId) {
				console.error('未找到分切复卷工序');
				return;
			}
			
			// 调用新的API获取工序记录
			const stepResult = await ProcessService.getProcessStepByIds(app.code, processId);
			
			if (stepResult.code === 200 && stepResult.data && stepResult.data.length > 0) {
				console.log('已存在工序记录:', stepResult.data);
				
				// 存储所有记录
				processRecords.value = stepResult.data;
				hasExistingRecord.value = true;
				
				// 为了兼容性，仍然设置第一个记录为主记录
				processRecord.value = stepResult.data[0];
				
				// 根据现有记录预填充规格数据
				// 先清空现有的规格项，重新填充
				formState.specItems = [];
				savedExceptions.value = []; // 清空已保存的异常记录
				
				for (let index = 0; index < stepResult.data.length; index++) {
					const record = stepResult.data[index];
					
					// 使用 smallRollModel 和 smallRollSpecification 组合回显
					let specName = '';
					if (record.smallRollModel && record.smallRollSpecification) {
						specName = `${record.smallRollModel}(${record.smallRollSpecification})`;
					}
					
					// 加载该规格的异常事件（存储到单独的数组中）
					const specExceptions = [];
					try {
						if (record.id) {
							const exceptionResult = await ProcessService.getProcessStepExceptions(app.code, record.id);
							if (exceptionResult.code === 200 && exceptionResult.data) {
								// 将异常记录转换为显示格式
								exceptionResult.data.forEach(exception => {
									specExceptions.push({
										exceptionName: exception.exceptionName, // 使用 exceptionName
										createTime: exception.createTime // 使用 createTime
									});
								});
								console.log(`规格${index + 1}的异常事件:`, specExceptions);
							}
						}
					} catch (error) {
						console.error(`加载规格${index + 1}异常事件失败:`, error);
					}
					
					// 存储该规格的已保存异常记录
					savedExceptions.value[index] = specExceptions;
					
					// 查找对应的smallRollId
					let smallRollId = '';
					if (record.smallRollModel && record.smallRollSpecification) {
						console.log(`查找规格匹配: model=${record.smallRollModel}, specification=${record.smallRollSpecification}`);
						// 直接通过 smallRollModel 和 smallRollSpecification 查找对应的 smallRollId
						const matchingSpec = allSpecifications.value.find(spec => 
							spec.model === record.smallRollModel && 
							spec.specification === record.smallRollSpecification
						);
						if (matchingSpec) {
							smallRollId = matchingSpec.smallRollId;
							console.log(`找到匹配的规格ID: ${smallRollId}`);
						} else {
							console.log('未找到匹配的规格');
						}
					}
					
					// 添加规格项（注意：step_6的说明是全局的，不是单个规格的）
					formState.specItems.push({
						specification: specName,
						length: Number(record.productionLength) || 0,
						linkCount: record.jointsCount || 0,
						smallRollId: smallRollId, // 小卷规格ID
						events: [] // 初始化为空数组，用于存储新添加的事件
					});
					
					// 如果是第一个记录，回显说明
					if (index === 0 && record.description) {
						formState.note = record.description;
					}
				}
				
				console.log('预填充后的规格项:', formState.specItems);
				
				// 异常事件已经在上面的循环中加载到 formState.specItems[].events 中了
			} else {
				console.log('暂无工序记录');
				hasExistingRecord.value = false;
				processRecords.value = [];
				savedExceptions.value = []; // 清空已保存的异常记录
			}
		} catch (error) {
			console.error('加载工序记录失败:', error);
		}
	};
	

	// 加载异常事件数据
	const loadExceptionEvents = async () => {
		try {
			const response = await ExceptionService.getExceptionList(1, 10);
			if (response && response.rows && Array.isArray(response.rows)) {
				// 将异常事件数据转换为actions格式，保存异常ID和名称
				record.actions = response.rows
					.filter(item => item.exceptionName) // 过滤掉没有名称的项
					.map(item => ({
						name: item.exceptionName,
						exceptionId: item.id || item.exceptionId // 保存异常ID
					}));
			} else {
				record.actions = [];
			}
		} catch (error) {
			console.error('加载异常事件失败:', error);
			record.actions = [];
		}
	};

	const onSubmit = async () => {
		// 如果已存在记录，询问用户是否要更新
		if (hasExistingRecord.value) {
			uni.showModal({
				title: '提示',
				content: '该工序已有记录，是否要更新？',
				success: async (res) => {
					if (res.confirm) {
						await submitProcessStep();
					}
				}
			});
		} else {
			await submitProcessStep();
		}
	};

	const submitProcessStep = async () => {
		toast.loading('保存中...')
		try {
			if (!app.code) {
				toast.error("流程卡号不存在");
				return;
			}
			
			const processId = await getProcessId();
			if (!processId) {
				toast.error("未找到分切复卷工序");
				return;
			}
			
			const currentTime = new Date().toISOString();
			let allSuccess = true;
			const results = [];
			
			// 为每个规格创建单独的工序记录
			for (let i = 0; i < formState.specItems.length; i++) {
				const item = formState.specItems[i];
				
				// 准备该规格的事件异常数据
				const specEvents = [];
				if (item.events && item.events.length > 0) {
					item.events.forEach(event => {
						if (event.exceptionId) { // 只保存有异常ID的事件
							specEvents.push({
								processCardId: app.code,
								exceptionId: event.exceptionId // 使用正确的异常ID
							});
						}
					});
				}
				
				try {
					let response;
					// 检查是否已存在该规格的记录（按索引匹配）
					const existingRecords = processRecords.value || [];
					const existingRecord = existingRecords[i]; // 按索引匹配对应的记录
					
					if (existingRecord && existingRecord.id) {
						// 修改现有记录
						const editRequest: EditProcessStepRequest = {
							id: existingRecord.id,
							processCardId: app.code,
							processId: processId,
							// productionType 不传，让后端自行处理
							productionLength: String(item.length || 0),
							productionTime: currentTime,
							jointsCount: Number(item.linkCount) || 0,
							description: i === 0 ? (formState.note || '') : '', // 只在第一条记录中保存说明
							smallRollId: item.smallRollId || '', // 小卷规格ID
							processStepException: specEvents
						};
						response = await ProcessService.editProcessStep(editRequest);
					} else {
						// 新增记录
						const addRequest: AddProcessStepRequest = {
							processCardId: app.code,
							processId: processId,
							// productionType 不传，让后端自行处理
							productionLength: String(item.length || 0),
							productionTime: currentTime,
							jointsCount: Number(item.linkCount) || 0,
							description: i === 0 ? (formState.note || '') : '', // 只在第一条记录中保存说明
							smallRollId: item.smallRollId || '', // 小卷规格ID
							processStepException: specEvents
						};
						response = await ProcessService.addProcessStep(addRequest);
					}
					
					results.push({
						spec: item.specification || `规格${i + 1}`,
						success: response.code === 200,
						message: response.msg
					});
					
					if (response.code !== 200) {
						allSuccess = false;
					}
				} catch (error) {
					console.error(`规格${i + 1}保存失败:`, error);
					results.push({
						spec: item.specification || `规格${i + 1}`,
						success: false,
						message: error.message || '保存失败'
					});
					allSuccess = false;
				}
			}
			
			if (allSuccess) {
				toast.success('所有规格保存成功');
				// 更新状态
				hasExistingRecord.value = true;
				await loadProcessStepRecord(); // 重新加载记录
				setTimeout(() => {
					uni.navigateBack();
				}, 1000);
			} else {
				// 显示部分成功的结果
				const failedSpecs = results.filter(r => !r.success).map(r => r.spec);
				toast.error(`部分规格保存失败: ${failedSpecs.join(', ')}`);
			}
		} catch (error) {
			console.error('保存失败:', error);
			toast.error("保存失败，请重试!")
		} finally {
			toast.close();
		}
	}
</script>

<style scoped>
	.layout {
		padding: 16rpx;
	}

	:deep(.wd-cell__left) {
		width: 120px !important;
		flex: none;
	}

	/* 确保只读状态的规格文字颜色清晰可见 */
	:deep(.wd-input.wd-input--readonly .wd-input__value) {
		color: #323233 !important; /* 使用正常的文字颜色 */
	}

	/* 规格状态区域样式 */
	.spec-status-section {
		margin-bottom: 8px;
	}

	/* 规格基本信息样式 */
	:deep(.spec-basic-info .wd-cell__title) {
		font-weight: 600;
		color: #1989fa;
	}

	/* 异常信息样式 */
	:deep(.spec-exception-info .wd-cell__title) {
		color: #ee0a24;
		font-size: 14px;
	}

	:deep(.spec-exception-info .wd-cell__value) {
		color: #969799;
		font-size: 12px;
	}

	/* 无异常样式 */
	:deep(.spec-no-exception .wd-cell__title) {
		color: #969799;
		font-size: 14px;
	}

	.total-length {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 10px 16px;
		background-color: #f5f5f5;
		margin-bottom: 10px;
		border-radius: 4px;
	}

	.spec-item {
		margin-bottom: 15px;
		padding: 10px;
		border: 1px solid #ebedf0;
		border-radius: 4px;
		background-color: #f8f8f8;
	}

	.spec-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 10px;
		padding-bottom: 5px;
		border-bottom: 1px solid #ebedf0;
	}

	.spec-title {
		font-weight: bold;
		font-size: 16px;
	}
	
	.spec-events {
		margin-top: 15px;
		padding-top: 15px;
		border-top: 1px solid #ebedf0;
	}
	
	.events-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 10px;
	}
	
	.events-title {
		font-weight: 500;
		font-size: 14px;
		color: #333;
	}
	
	.events-list {
		background-color: #fff;
		border-radius: 4px;
		overflow: hidden;
	}
	
	.event-item {
		border-bottom: 1px solid #f0f0f0;
	}
	
	.event-item:last-child {
		border-bottom: none;
	}
	
	.no-events {
		text-align: center;
		padding: 20rpx;
		background-color: #f9f9f9;
		border-radius: 4px;
	}
	
	.no-events-text {
		color: #999;
		font-size: 24rpx;
	}
	
	/* 规格选择弹窗样式 */
	.spec-popup {
		height: 100%;
		display: flex;
		flex-direction: column;
		background-color: #fff;
	}
	
	.spec-popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 16px;
		border-bottom: 1px solid #ebedf0;
		background-color: #f8f8f8;
	}
	
	.spec-popup-title {
		font-size: 18px;
		font-weight: 600;
		color: #323233;
	}
	
	.spec-search {
		padding: 12px 16px;
		background-color: #f8f8f8;
		border-bottom: 1px solid #ebedf0;
	}
	
	.spec-list {
		flex: 1;
		overflow-y: auto;
	}
	
	.spec-empty {
		text-align: center;
		padding: 40px 20px;
		color: #969799;
	}
	
	.spec-empty-text {
		font-size: 14px;
		color: #969799;
	}
</style>